package com.ch.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ch.web.ResponseDto.xyTalk.TalkResponseDto;
import com.ch.web.ResponseDto.xyComment.XyCommentResponse;
import com.ch.web.entity.user.XyCommentEntity;
import com.ch.web.entity.user.XyTalkEntity;
import com.ch.web.entity.user.XyUserEntity;
import com.ch.web.mapper.XyTalkDao;
import com.ch.web.redis.UserMapCache;
import com.ch.web.requestDto.xyTalk.request.XyTalkAddRequest;
import com.ch.web.requestDto.xyTalk.response.XyTalkAdminListResponse;
import com.ch.web.requestDto.xyTalk.response.XyTalkMyListResponse;
import com.ch.web.service.*;
import com.ch.web.utils.ColaBeanUtils;
import com.ch.web.utils.PageUtils;
import com.ch.web.utils.Query;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.stream.Collectors;


@Service("xyTalkService")
public class XyTalkServiceImpl extends ServiceImpl<XyTalkDao, XyTalkEntity> implements XyTalkService {

    @Autowired
    XyTokenService xyTokenService;
    @Autowired
    XyUserService xyUserService;

    @Autowired
    XyCommentService xyCommentService;

    @Autowired
    XyBackCommentService xyBackCommentService;
    @Autowired
    XyTalkImagesService xyTalkImagesService;
    @Autowired
    XyGzService xyGzService;
    @Autowired
    ThreadPoolService threadPoolService;
    @Autowired
    XyDzService xyDzService;
    @Autowired
    XyScService xyScService;
    @Resource
    UserMapCache userMapCache;

    @Override
    public List<TalkResponseDto> queryPage(Map<String, Object> map, HttpServletRequest request) {
        String userNick = (String) map.get("searChText");
        QueryWrapper<XyTalkEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userNick)) {
            Long aLong = xyUserService.geUserIdByUserNick(userNick);
            wrapper.eq("user_id", aLong);
        }
        wrapper.orderByAsc("create_time");
        IPage<XyTalkEntity> page = this.page(
                new Query<XyTalkEntity>().getPage(map),
                new QueryWrapper<>()
        );
        List<XyTalkEntity> records = page.getRecords();
        return this.getTalkAllInfo(records, request);

    }

    @Override
    public boolean addShareTalk(XyTalkAddRequest addRequest, HttpServletRequest request) {
        //发表说说的人
        XyUserEntity userEntityBYToken = userMapCache.getUserEntityBYToken(request);
        XyTalkEntity talkEntity = ColaBeanUtils.copyObject(addRequest, XyTalkEntity::new);
        talkEntity.setUserId(userEntityBYToken.getUserId());
        this.save(talkEntity);
        Long talkId = talkEntity.getId();
        xyTalkImagesService.addTalkImages(talkId, addRequest.getImageUrls());
        return true;
    }

    @Override
    public PageUtils getUserTalkList(Map<String, Object> map, HttpServletRequest request) {
        XyUserEntity userEntity = userMapCache.getUserEntityBYToken(request);
        QueryWrapper<XyTalkEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userEntity.getUserId());
        IPage<XyTalkEntity> page = this.page(
                new Query<XyTalkEntity>().getPage(map),
                wrapper
        );
        List<XyTalkEntity> collect = page.getRecords().stream().map(xyTalkEntity -> {
            XyTalkMyListResponse xyTalkMyListResponse = ColaBeanUtils.copyObject(xyTalkEntity, XyTalkMyListResponse::new);
            xyTalkMyListResponse.setUserNick(userEntity.getUserNick());
            xyTalkMyListResponse.setUserAva(userEntity.getUserAva());
            return xyTalkMyListResponse;
        }).collect(Collectors.toList());
        page.setRecords(collect);
        return new PageUtils(page);
    }

    @Override
    public List<TalkResponseDto> getSelfTalk(Long talkId, HttpServletRequest request) {
        XyTalkEntity entity = this.getById(talkId);
        List<XyTalkEntity> xyTalkEntities = Collections.singletonList(entity);
        return getTalkAllInfo(xyTalkEntities, request);
    }

    @Override
    public Boolean selfDeleteTalkById(Long id) {
        return this.removeById(id) && this.xyTalkImagesService.deleteImagesByTalkId(id) && this.xyCommentService.deleteCommentByTalkId(id);
    }

    @Override
    public PageUtils adminGetList(Map<String, Object> map, HttpServletRequest request) {
        QueryWrapper<XyTalkEntity> queryWrapper = new QueryWrapper<>();
        String talkContent = (String) map.get("talkContent");
        if (StringUtils.isNotBlank(talkContent)) {
            queryWrapper.like("content", talkContent);
        }
        String sendTalkUser = (String) map.get("sendTalkUser");
        if (StringUtils.isNotBlank(sendTalkUser)) {
            Long id = xyUserService.geUserIdByUserNick(sendTalkUser);
            if (ObjectUtils.isNotEmpty(id)) {
                queryWrapper.eq("user_id", id);
            }
        }
        IPage<XyTalkEntity> page = this.page(
                new Query<XyTalkEntity>().getPage(map),
                queryWrapper
        );
        page.setRecords(page.getRecords().stream().map(xyTalkEntity -> {
            XyTalkAdminListResponse response = new XyTalkAdminListResponse();
            BeanUtils.copyProperties(xyTalkEntity, response);
            response.setUserNick(xyUserService.getById(xyTalkEntity.getUserId()).getUserNick());
            return response;
        }).collect(Collectors.toList()));
        return new PageUtils(page);

    }

    public List<TalkResponseDto> getTalkAllInfo(List<XyTalkEntity> xyTalkEntities, HttpServletRequest request) {
        System.out.println(LocalDateTime.now());
        String token = request.getHeader("token");
        //当前用户id
        Long currentUserId = xyTokenService.getUserIdByToken(token);
        CountDownLatch countDownLatch = new CountDownLatch(xyTalkEntities.size());
        List<TalkResponseDto> collect = new ArrayList<>(xyTalkEntities.size());
        xyTalkEntities.forEach(talk -> {
            threadPoolService.getExecutor().execute(() -> {
                //每次查询一次 就进行count++
                int count = talk.getCount();
                talk.setCount(++count);
                //增加浏览次数
                this.saveOrUpdate(talk);
                TalkResponseDto talkResponseDto = ColaBeanUtils.copyObject(talk, TalkResponseDto::new);
                try {
                    //说说主键id
                    Long talkId = talkResponseDto.getId();
                    //userId用来查这个人的信息
                    Long userId = talk.getUserId();
                    XyUserEntity userInfo = xyUserService.getById(userId);
                    talkResponseDto.setXyUserEntity(userInfo);
                    //判断是否点赞
                    talkResponseDto.setIsDz(xyDzService.getIsDZ(talkId, currentUserId));
                    //判断是否收藏
                    talkResponseDto.setIsSc(xyScService.getIsSc(talkId, currentUserId));
                    //判断当前查询的人和说说的人是否是关注关系
                    talkResponseDto.setIsGz(xyGzService.getIsGzUser(currentUserId, userId));
                    //查询哪些人点赞了这个说说  显示10个范围 其他的隐藏
                    talkResponseDto.setUserEntityDzTalkRes(xyUserService.getDZPersons(talkId));
                    //查询评论
                    List<XyCommentEntity> commentEntities = xyCommentService.getCommentByTalkId(talkId);
                    if (commentEntities.size() > 0) {
                        List<XyCommentResponse> commentResponses = ColaBeanUtils.copyListProperties(commentEntities, XyCommentResponse::new);
                        //查询每个评论下的互动评论
                        commentResponses.forEach(commentResponse -> {
                            //查询评论人的信息
                            XyUserEntity userEntity = xyUserService.getById(commentResponse.getUserId());
                            commentResponse.setXyUserEntity(userEntity);
                            //根据当前这个评论的id  去查互动的数据
                            commentResponse.setXyBackCommentResponses(xyBackCommentService.getBackByCommentId(commentResponse.getId()));
                        });
                        talkResponseDto.setXyCommentResponseList(commentResponses);
                    }
                    //查询图片
                    talkResponseDto.setXyImages(xyTalkImagesService.getImagesByTalkId(talkId));
                } finally {
                    countDownLatch.countDown();
                    collect.add(talkResponseDto);
                }
            });
        });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        collect.forEach(System.out::println);
        return collect;
    }
}
